/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.PostConstruct;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.lmx.common.constants.CommonConstants;
import com.lmx.common.constants.ICommonConstants;
import com.lmx.persistence.service.CommonService;
import com.lmx.persistence.service.CustomerServiceItemService;
import com.lmx.persistence.service.RolePrivilegeService;
import com.lmx.persistence.service.TenantPrivilegeService;
import com.lmx.persistence.service.TenantService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.Tenant;//huibati

import io.katharsis.queryParams.QueryParams;
import io.katharsis.repository.annotations.JsonApiFindAll;
import io.katharsis.repository.annotations.JsonApiFindOne;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

@JsonApiResourceRepository(Tenant.class)
@Component
public class TenantRepository extends BaseRepository<Tenant> {

	@Autowired
	private CommonService commonService;

	@Autowired
	private TenantService<Tenant> tenantService;
	@Autowired
	private TenantPrivilegeService tenantPrivilegeSrv;
	@Autowired
	private RolePrivilegeService rolePrivilegeSrv;
	@Autowired
	private CustomerServiceItemService customerServiceItemSrv;

	Log logger = LogFactory.getLog(this.getClass());
	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(Tenant.class);
	}

	@SuppressWarnings("unchecked")
	@Override
	@JsonApiSave
	public Tenant save(Tenant tenant) {
		if (tenant.getId() == null) {
			// 手机号查重 huibati
			List<Tenant> data = tenantService.getTenantByTel(tenant.getLinkManTel());
			if (data == null || data.size() == 0) {
				tenant.setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.TENANT_STATUS_2
						.label()));
				dslJpaService.create(tenant); 
				//this.customerServiceItemSrv.createDefault(tenant);
			} else {
				tenant.setErrcode(5);// 联系人电话重复
				throw new BusinessException(null, CommonConstants.ERROR_CODE.PHONE_ERROR.label(),
						null);
			}
		} else {
			if (tenant.getDelStatus() == 1) {// 删除 修改相关权限
				tenant.setStatus(commonService.getDicttype(CommonConstants.DICTTYPE.TENANT_STATUS_3.label()));
				// 操作 该租户相关权限功能以及用户
				dslJpaService.update(tenant);
			} else {
				Tenant tenantTemp = tenantService.getTenantById(tenant.getId());
				//补充机构权限
				if(tenant.getDesc()!=null&&"alljigou".equals(tenant.getDesc())){
					tenant.setDesc("");
					tenantService.addAllPrivilegeData(tenant,"1");
					return tenant;
				}
				if(tenant.getDesc()!=null&&"alljujia".equals(tenant.getDesc())){
					tenant.setDesc("");
					tenantService.addAllPrivilegeData(tenant,"2");
					return tenant;
				}
				if (tenant.getAllJiGou() == ICommonConstants.COMMON_STATUS.YES.label()) {
					this.tenantPrivilegeSrv.allocateSysPrivilege(tenant,
							ICommonConstants.SYSTEM_TYPE_JIGOU_1);
					tenantService.operateTenantRole(tenant);// 修改租户角色权限数据
					return tenant;
				}
				if (tenant.getAllJuJia() == ICommonConstants.COMMON_STATUS.YES.label()) {
					this.tenantPrivilegeSrv.allocateSysPrivilege(tenant,
							ICommonConstants.SYSTEM_TYPE_JUJIA_2);
					tenantService.operateTenantRole(tenant);// 修改租户角色权限数据
					return tenant;
				}
				if (tenant.getAllPublic() == ICommonConstants.COMMON_STATUS.YES.label()) {
					this.rolePrivilegeSrv.allocatePublicPrivilege(tenant);
					return tenant;
				}
				//dslJpaService.update(tenant);
				//tenantService.updatePrivilege(tenant, ActionContextHolder.getContext().getPayloadDatas());
				
				// 未发布--->发布 产生新的 org role+(所选择权限) + adminUser
				if (CommonConstants.DICTTYPE.TENANT_STATUS_2.label().equals(
						tenantTemp.getStatus().getTypecode())
						&& CommonConstants.DICTTYPE.TENANT_STATUS_1.label().equals(
								tenant.getStatus().getTypecode())) {
					tenantService.operateTenantReleased(tenant);
					return tenant;
				}
//				if (CommonConstants.DICTTYPE.TENANT_STATUS_1.label().equals(
//						tenantTemp.getStatus().getTypecode())
//						&& CommonConstants.DICTTYPE.TENANT_STATUS_1.label().equals(
//								tenant.getStatus().getTypecode())) { // 待修改如果状态未修改
//					tenantService.operateTenantRole(tenant);// 修改租户角色权限数据
//				}
				// 发布--->未发布/下线
				if (CommonConstants.DICTTYPE.TENANT_STATUS_1.label().equals(
						tenantTemp.getStatus().getTypecode())
						&& (CommonConstants.DICTTYPE.TENANT_STATUS_3.label().equals(
								tenant.getStatus().getTypecode()) || CommonConstants.DICTTYPE.TENANT_STATUS_2
								.label().equals(tenant.getStatus().getTypecode()))) {

				}
			}
			tenantService.updateOrgByTenant(tenant);
		}
		return tenant;
	}

	@Override
	@JsonApiFindAll
	public Iterable<Tenant> findAll(final QueryParams requestParams) {
		Iterable<Tenant> tenants = super.findAll(requestParams);
		List<Tenant> tenants2 = new ArrayList<>();
		for (Tenant tenant : tenants) {
			if (tenant.getDelStatus() == 0) {
				tenants2.add(tenant);
			}
		}
		return tenants2;
	}

	@Override
	@JsonApiFindOne
	public Tenant findOne(final Long id, final QueryParams requestParams) {
		Tenant tenant = super.findOne(id, requestParams);
		this.tenantPrivilegeSrv.addPrivileges(tenant);
		return tenant;
	}
}
